--[[ $Id: Core.lua 152 2008-04-28 10:54:25Z kuchen_@gmx.de $ ]]
local MultiItemRef = LibStub("AceAddon-3.0"):NewAddon("MultiItemRef", "AceHook-3.0")
_G.MultiItemRef = MultiItemRef

local openLinks = {}
local linkTypes = {
	item = true,
	enchant = true,
	spell = true, -- patch 2.4
	quest = true, -- patch 2.4
}

local NewTooltip, DelTooltip

function MultiItemRef:OnEnable()
	self:RawHook("SetItemRef", true)
end

local function IsLink(link)
	for t in pairs(linkTypes) do
		if link:sub(1,#t) == t then
			return true
		end
	end
	return false
end

function MultiItemRef:SetItemRef(link, text, button)
	if IsLink(link) and not IsModifiedClick() then
		self:Show(link)
	else
		return self.hooks.SetItemRef(link, text, button)
	end
end

function MultiItemRef:Show(itemLink)
	local frame = openLinks[itemLink]
	if frame then
		frame:Hide()
	else
		frame = NewTooltip()
		frame.link = itemLink
		frame:SetOwner(UIParent, "ANCHOR_PRESERVE")
		-- DO NOT CALL frame:Show(), it causes frame to be hidden and the owner to be cleared. I *hate* theese tooltips
		frame:SetHyperlink(itemLink)
		openLinks[itemLink] = frame
	end
end

do 
	local idCounter = 0
	local tooltips = {}
	
	local function Frame_OnDragStart(self)
		self:StartMoving()
	end

	local function Frame_OnDragStop(self)
		self:StopMovingOrSizing()
	end

	local function Frame_OnHide(self)
		openLinks[self.link] = nil
		DelTooltip(self)
	end

	local function Button_OnClick(self)
		self.frame:Hide()
	end	

	local function CreateItemFrame()
		local id = idCounter + 1
		idCounter = id
		
		local f = CreateFrame("GameTooltip", "MultiItemRefFrame"..id, UIParent, "GameTooltipTemplate")
		f.id = id
		f:EnableMouse(true)
		f:SetMovable(true)
		f:SetToplevel(true)
		f:SetWidth(128)
		f:SetHeight(64)
		f:SetPadding(16)
		f:SetPoint("BOTTOM", 0, 80)
		f:RegisterForDrag("LeftButton")

		local b = CreateFrame("Button", nil, f)
		b:SetWidth(32)
		b:SetHeight(32)
		b:SetPoint("TOPRIGHT", f, "TOPRIGHT", 1, 0)
		b:SetNormalTexture("Interface\\Buttons\\UI-Panel-MinimizeButton-Up")
		b:SetPushedTexture("Interface\\Buttons\\UI-Panel-MinimizeButton-Down")
		b:SetHighlightTexture("Interface\\Buttons\\UI-Panel-MinimizeButton-Highlight")
		b:SetScript("OnClick", Button_OnClick)
		b:SetFrameLevel(f:GetFrameLevel() + 1)

		b.frame = f
		f.closeButton = b

		f:SetScript("OnDragStart", Frame_OnDragStart)
		f:SetScript("OnDragStop", Frame_OnDragStop)
		f:SetScript("OnHide", Frame_OnHide)

		_G.this = f
		_G.GameTooltip_OnLoad() -- takes no argument, so global this
		
		return f
	end
	
	function NewTooltip()
		local tt = tremove(tooltips)
		if not tt then
			tt = CreateItemFrame()
		end
		return tt
	end
	
	function DelTooltip(tt)
		tt:Hide()
		tinsert(tooltips, tt)
	end
end
